﻿using System;
using System.Windows;
using System.Windows.Controls;
using System.Data.SqlClient;
using System.Windows.Forms;
using System.IO;
using ClosedXML.Excel;
using System.Timers;
using System.Collections.Generic;
using DocumentFormat.OpenXml.InkML;
using HandyControl.Controls;
using black_screen_mode_server.Models;
using System.Data;
using DocumentFormat.OpenXml.Vml.Office;
using System.Configuration;
using System.Diagnostics.Metrics;
using DocumentFormat.OpenXml.EMMA;
using System.Threading;


namespace black_screen_mode_server.Pages
{
    /// <summary>
    /// TimedFormPage.xaml 的交互逻辑
    /// </summary>
    public partial class TimedFormPage : Page
    {
        public enum ReportType
        {
            Daily,
            Weekly,
            Monthly
        }

        private DateTime initExportTime;

        public TimedFormPage()
        {
            InitializeComponent();
            initExportTime = DateTime.Now;
            UpdateLastExportTime(initExportTime.ToString("yyyy-MM-dd HH:mm:ss"));
            LoadLocationDataFromDatabase();
        }

        //数据库连接
        private string connectionString = ProjectTools.configDbConnString;// "server=LAPTOP-CKCFDD72;Database=TestDatabase;User Id=sa;Password=bageling;";

        //选择本地文件存储路径
        private void btnSelectLocalFolderDialog_Click(object sender, RoutedEventArgs e)
        {
            using (FolderBrowserDialog folderBrowserDialog = new FolderBrowserDialog())
            {
                folderBrowserDialog.Description = "请选择文件夹";
                folderBrowserDialog.ShowNewFolderButton = true;

                if (folderBrowserDialog.ShowDialog() == DialogResult.OK)
                {
                    txtLocalFileLocation.Text = folderBrowserDialog.SelectedPath;
                }
            }
        }

        public void StartFunctions()
        {
            InitializeTimer();
        }

        public void StopFunctions()
        {
            timer.Stop();
            dailyTimer.Change(Timeout.Infinite, Timeout.Infinite);
            weeklyTimer.Change(Timeout.Infinite, Timeout.Infinite);
            monthlyTimer.Change(Timeout.Infinite, Timeout.Infinite);
        }

        //选择网络文件存储路径
        private void btnSelectNetFolderDialog_Click(object sender, RoutedEventArgs e)
        {
            using (FolderBrowserDialog folderBrowserDialog = new FolderBrowserDialog())
            {
                folderBrowserDialog.Description = "请选择文件夹";
                folderBrowserDialog.ShowNewFolderButton = true;

                if (folderBrowserDialog.ShowDialog() == DialogResult.OK)
                {
                    txtNetFileLocation.Text = folderBrowserDialog.SelectedPath;
                }
            }
        }

        //保存更改
        private void btnFormConfirm_Click(object sender, RoutedEventArgs e)
        {
            try
            {
                ProjectTools.WriteConfig("parametersInfo", "file_location_local", txtLocalFileLocation.Text);
                ProjectTools.WriteConfig("parametersInfo", "file_location_net", txtNetFileLocation.Text);
                ProjectTools.WriteConfig("parametersInfo", "interval", txtInterval.Text);

                //ConfigurationTools.configuration.GetSection("parametersInfo")["file_location_local"] = txtLocalFileLocation.Text;
                //ConfigurationTools.configuration.GetSection("parametersInfo")["file_location_net"] = txtNetFileLocation.Text;
                //ConfigurationTools.configuration.GetSection("parametersInfo")["interval"] = txtInterval.Text;

                if (timer != null)
                {
                    timer.Interval = GetIntervalTime() * 60 * 60 * 1000;
                }
                System.Windows.Forms.MessageBox.Show("更新成功！", "提示");
            }
            catch (Exception)
            {
                System.Windows.Forms.MessageBox.Show("更新失败！", "提示");
            }
        }

        //初始化加载
        private void LoadLocationDataFromDatabase()
        {
            txtLocalFileLocation.Text = ProjectTools.ReadConfig("parametersInfo", "file_location_local");
            txtNetFileLocation.Text = ProjectTools.ReadConfig("parametersInfo", "file_location_net");
            txtInterval.Text = ProjectTools.ReadConfig("parametersInfo", "interval");

            //txtLocalFileLocation.Text = ConfigurationTools.configuration.GetSection("parametersInfo")["file_location_local"];
            //txtNetFileLocation.Text = ConfigurationTools.configuration.GetSection("parametersInfo")["file_location_net"];
            //txtInterval.Text = ConfigurationTools.configuration.GetSection("parametersInfo")["interval"];
        }


        /// <summary>
        /// 定时报表导出
        /// </summary>
        private System.Timers.Timer timer;


        //每日报表导出定时器
        private System.Threading.Timer dailyTimer;

        //每周报表导出定时器
        private System.Threading.Timer weeklyTimer;

        //每月报表导出定时器
        private System.Threading.Timer monthlyTimer;

        private void InitializeTimer()
        {
            timer = new System.Timers.Timer();
            timer.Elapsed += Timer_Elapsed;
            timer.Interval = GetIntervalTime() * 60 * 60 * 1000;
            //timer.Interval = 2 * 60 * 1000;
            timer.AutoReset = true;
            timer.Start();

            DateTime current = DateTime.Now;
            dailyTimer = new System.Threading.Timer(DailyReportTask);
            SetDailyReportFixedTime(current);
            weeklyTimer = new System.Threading.Timer(WeeklyReportTask);
            setWeeklyReportFixedTime(current);
            monthlyTimer = new System.Threading.Timer(MothlyReportTask);
            setMonthlyReportFixedTime(current);

        }

        private void Timer_Elapsed(object sender, ElapsedEventArgs e)
        {
            try
            {
                string location1 = ProjectTools.ReadConfig("parametersInfo", "file_location_local");
                string location2 = ProjectTools.ReadConfig("parametersInfo", "file_location_net");

                //string location1 = ConfigurationTools.configuration.GetSection("parametersInfo")["file_location_local"];
                //string location2 = ConfigurationTools.configuration.GetSection("parametersInfo")["file_location_net"];

                string fileName = $"Report_{DateTime.Now.ToString("yyyyMMddHHmm")}.xlsx";
                string dtLastExport = GetLastExportTime();
                DateTime dt = DateTime.Now;
                string currentTime = dt.ToString("yyyy-MM-dd HH:mm:ss");
                ProjectTools.ExportDataToExcel(location1, fileName,dtLastExport, currentTime);
                CopyFile(location1, location2, fileName);
            }
            catch (Exception ex)
            {
                Logger.Singleton.Error("生成定时报表错误");
                System.Windows.MessageBox.Show($"错误: {ex.Message}", "提示");
            }
        }
        //获取上次导出时间
        private string GetLastExportTime()
        {
            return ProjectTools.ReadConfig("parametersInfo", "last_export_time");

            //return ConfigurationTools.configuration.GetSection("parametersInfo")["last_export_time"];
        }

        //获取导出间隔时间
        private int GetIntervalTime()
        {
            try
            {
                return int.Parse(ProjectTools.ReadConfig("parametersInfo", "interval"));

                //return ConfigurationTools.configuration.GetSection("parametersInfo")["interval"];
            }
            catch (Exception ex)
            {
                return 24;
            }

        }



        //更新上次导出时间
        private void UpdateLastExportTime(string currentTime)
        {
            ProjectTools.WriteConfig("parametersInfo", "last_export_time", currentTime);

            //ConfigurationTools.configuration.GetSection("parametersInfo")["last_export_time"] = currentTime.ToString("yyyy-MM-dd HH:mm:ss");
        }
        //备份保存至网络地址
        private void CopyFile(string sourceLocation, string destinationLocation, string fileName)
        {
            string sourcePath = Path.Combine(sourceLocation, fileName);
            string destinationPath = Path.Combine(destinationLocation, fileName);
            File.Copy(sourcePath, destinationPath, true);
        }

        private void btnQueryForm_Click(object sender, RoutedEventArgs e)
        {
            FormQuery formQuery = new FormQuery();
            formQuery.Show();
        }

        public void SetDailyReportFixedTime(DateTime current)
        {
            DateTime dailyT = DateTime.Today.AddHours(8);
            if (current > dailyT)
            {
                dailyT = dailyT.AddDays(1);
            }
            long msFirstInterval = (int)((dailyT - current).TotalMilliseconds);
            long interval = 24 * 60 * 60 * 1000;
            dailyTimer.Change(msFirstInterval, interval);
        }

        public void setWeeklyReportFixedTime(DateTime current)
        {
            int dayOfWeek = (int)current.DayOfWeek;
            DateTime weeklyT = DateTime.Today.AddDays(7 - dayOfWeek).AddHours(8);
            if (current > weeklyT)
            {
                weeklyT = weeklyT.AddDays(7);
            }
            long msFirstInterval = (long)((weeklyT - current).TotalMilliseconds);
            long interval = 7 * 24 * 60 * 60 * 1000;
            weeklyTimer.Change(msFirstInterval, interval);
        }

        public void setMonthlyReportFixedTime(DateTime current)
        {
            int dayOfMonth = current.Day;
            DateTime monthlyT = DateTime.Today.AddDays(DateTime.DaysInMonth(current.Year, current.Month) - dayOfMonth +1).AddHours(8);
            if (current > monthlyT)
            {
                monthlyT = monthlyT.AddMonths(1);
            }
            long msFirstInterval = (long)((monthlyT - current).TotalMilliseconds);
           // int interval = DateTime.DaysInMonth(current.Year, current.Month) * 24 * 60 * 60 * 1000;
            monthlyTimer.Change(msFirstInterval, Timeout.Infinite);
        }

        public void SetReportFixedTime(ReportType t, Action<string, string, string, string> reportTask)
        {
            DateTime current = DateTime.Now;
            switch (t)
            {
                case ReportType.Daily:
                    {
                        DateTime dailyT = DateTime.Today.AddHours(8);
                        if(current > dailyT)
                        {
                            dailyT = dailyT.AddDays(1);
                        }
                        int msFirstInterval = (int)((dailyT - current).TotalMilliseconds);
                        int interval = 24 * 60 * 60 * 1000;
                        dailyTimer.Change(msFirstInterval, interval);
                        break;
                    }
                case ReportType.Weekly:
                    {
                        int dayOfWeek = (int)current.DayOfWeek;
                        DateTime weeklyT = DateTime.Today.AddDays(7 - dayOfWeek).AddHours(8);
                        if (current > weeklyT)
                        {
                            weeklyT = weeklyT.AddDays(7);
                        }
                        int msFirstInterval = (int)((weeklyT - current).TotalMilliseconds);
                        int interval = 7 * 24 * 60 * 60 * 1000;
                        weeklyTimer.Change(msFirstInterval, interval);
                    }
                    break;
                case ReportType.Monthly:
                    { 
                        int dayOfMonth = current.Day;
                        DateTime monthlyT = DateTime.Today.AddDays(DateTime.DaysInMonth(current.Year, current.Month) - dayOfMonth).AddHours(8);
                        if (current > monthlyT)
                        {
                            monthlyT = monthlyT.AddMonths(1);
                        }
                        int msFirstInterval = (int)((monthlyT - current).TotalMilliseconds);
                        int interval = DateTime.DaysInMonth(current.Year, current.Month) * 24 * 60 * 60 * 1000;
                        monthlyTimer.Change(msFirstInterval, interval);
                    }
                    break;
                default:
                    break;
            }
        }

        private void DailyReportTask(object? state)
        {
            try
            {
                DateTime current = DateTime.Now;
                ProjectTools.ExportDataToExcel(ProjectTools.ReadConfig("parametersInfo", "file_location_local"), $"DailyReport_{DateTime.Now.ToString("yyyyMMddHHmm")}.xlsx", current.AddDays(-1).ToString("yyyy-MM-dd HH:mm:ss"), current.ToString("yyyy-MM-dd HH:mm:ss"));
                ProjectTools.ExportDataToExcel(ProjectTools.ReadConfig("parametersInfo", "file_location_net"), $"DailyReport_{DateTime.Now.ToString("yyyyMMddHHmm")}.xlsx", current.AddDays(-1).ToString("yyyy-MM-dd HH:mm:ss"), current.ToString("yyyy-MM-dd HH:mm:ss"));

            }
            catch (Exception ex)
            {
                Logger.Singleton.Error("生成定时报表错误");
                return;
            }
           
        }

        private void WeeklyReportTask(object? state)
        {
            try
            {
                DateTime current = DateTime.Now;
                ProjectTools.ExportDataToExcel(ProjectTools.ReadConfig("parametersInfo", "file_location_local"), $"WeeklyReport_{DateTime.Now.ToString("yyyyMMddHHmm")}.xlsx", current.AddDays(-7).ToString("yyyy-MM-dd HH:mm:ss"), current.ToString("yyyy-MM-dd HH:mm:ss"));
                ProjectTools.ExportDataToExcel(ProjectTools.ReadConfig("parametersInfo", "file_location_net"), $"WeeklyReport_{DateTime.Now.ToString("yyyyMMddHHmm")}.xlsx", current.AddDays(-7).ToString("yyyy-MM-dd HH:mm:ss"), current.ToString("yyyy-MM-dd HH:mm:ss"));
            }
            catch (Exception)
            {
                Logger.Singleton.Error("生成周报表错误");
                return;
            }
          
        }

        private void MothlyReportTask(object? state)
        {
            try
            {
                DateTime current = DateTime.Now;
                ProjectTools.ExportDataToExcel(ProjectTools.ReadConfig("parametersInfo", "file_location_local"), $"MonthlyReport_{DateTime.Now.ToString("yyyyMMddHHmm")}.xlsx", current.AddMonths(-1).ToString("yyyy-MM-dd HH:mm:ss"), current.ToString("yyyy-MM-dd HH:mm:ss"));
                ProjectTools.ExportDataToExcel(ProjectTools.ReadConfig("parametersInfo", "file_location_net"), $"MonthlyReport_{DateTime.Now.ToString("yyyyMMddHHmm")}.xlsx", current.AddMonths(-1).ToString("yyyy-MM-dd HH:mm:ss"), current.ToString("yyyy-MM-dd HH:mm:ss"));
                setMonthlyReportFixedTime(current);
            }
            catch (Exception ex)
            {
                Logger.Singleton.Error("生成月报表错误");
                return;
            }
          
        }
    }
}
